from django.conf import settings
from django.contrib.auth import login as django_login, authenticate
import hashlib
from django.contrib.auth.models import User
import vkontakte
from apps.users.models import UserProfile
from services.vk import VKService

class TemplatesMiddleware(object):

    def process_request(self, request):

        #if "vk.com/" in request.META.get("HTTP_REFERER", ""):
	if request.META.get('SERVER_NAME', '') == "vkontakte.xoxot.com.ua":
            vk = VKService()

	    settings.LIVE_ENGINE_URL = "http://vkontakte.xoxot.com.ua"
            settings.LIVE_ENGINE_TEMPLATE = "vkontakte"
	    
            user_id = request.GET.get("viewer_id", "")
            auth_key = request.GET.get("auth_key", "")
            access_token = request.GET.get("access_token", "")
            
            if vk.get_auth_key(VKService.TYPE_VK_APPLICATION, user_id) == auth_key:
                try:
                  user = vk.get_user(VKService.TYPE_VK_APPLICATION, user_id, access_token)
                  auth_user = authenticate(
                      username = user.email,
                      password = auth_key
                  )
                  django_login(request, auth_user)

                  request.session['vk_user_access_token'] = access_token

                except Exception, e:
                  pass

        return None
